let currentMatchIndex = -1;
let totalMatches = 0;
let currentKeyword = '';
let currentHighlights = [];

// 添加关键句式规则
const keyPhraseRules = {
  transition: {
    color: '#FFD700', // 金色
    patterns: [
      '但是', '然而', '不过', '可是', '却',
      '尽管.*?但是?', '虽然.*?但是?', '但是.*?却',
      '即使.*?也', '无论.*?都', '固然.*?但是?',
      '反而', '相反', '反之'
    ]
  },
  causation: {
    color: '#98FB98', // 淡绿色
    patterns: [
      '因此', '所以', '导致', '由于', '因为',
      '之所以.*?是因为', '因为.*?所以',
      '基于', '鉴于', '考虑到',
      '致使', '引起', '造成',
      '结果是', '带来', '使得',
      '产生了.*?影响', '造成了.*?后果'
    ]
  },
  progression: {
    color: '#87CEEB', // 天蓝色
    patterns: [
      '不仅.*?而且', '不但.*?还', '甚至', '更', 
      '更重要的是', '尤其是', '特别是',
      '首先.*?其次.*?最后',
      '一方面.*?另一方面',
      '越来越', '日益', '逐渐',
      '进而', '并且', '同时'
    ]
  },
  summary: {
    color: '#DDA0DD', // 梅红色
    patterns: [
      '总的来说', '换句话说', '也就是说',
      '综上所述', '总而言之', '归根结底',
      '简而言之', '概括地说', '总的看来',
      '由此可见', '可见', '说明',
      '证明', '表明', '显示'
    ]
  },
  comparison: {
    color: '#FFA07A', // 浅鲑鱼色
    patterns: [
      '相比之下', '相较于', '与其.*?不如',
      '一方面.*?另一方面', '对比', '比较',
      '高于', '优于', '不同于',
      '区别在于', '差异在于',
      '相对来说', '相对而言'
    ]
  },
  emphasis: {
    color: '#FF69B4', // 粉红色
    patterns: [
      '值得注意的是', '需要注意的是', '注意',
      '重点是', '关键是', '核心是',
      '主要', '重要', '关键',
      '为什么.*?呢？', '怎么.*?呢？',
      '究竟.*?呢？', '到底.*?呢？',
      '显著', '明显', '突出'
    ]
  },
  definition: {
    color: '#40E0D0', // 绿松石色
    patterns: [
      '定义为', '指的是', '就是指',
      '即', '是指', '包括',
      '包含', '涉及', '涵盖',
      '例如', '比如', '譬如',
      '举例来说', '以.*?为例'
    ]
  }
};

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'highlight') {
    if (request.autoHighlight) {
      autoHighlightKeyPhrases();
    } else {
      currentKeyword = request.keyword;
      highlightKeyword(request.keyword, request.color);
    }
    sendResponse({ totalMatches, currentMatchIndex });
  } else if (request.action === 'clearHighlights') {
    clearHighlights();
    currentMatchIndex = -1;
    totalMatches = 0;
    currentKeyword = '';
    currentHighlights = [];
    sendResponse({ totalMatches });
  } else if (request.action === 'nextMatch') {
    if (totalMatches > 0) {
      navigateMatches(1);
    } else if (currentKeyword) {
      highlightKeyword(currentKeyword, request.color || '#ffff00');
    }
    sendResponse({ currentMatchIndex, totalMatches });
  } else if (request.action === 'prevMatch') {
    if (totalMatches > 0) {
      navigateMatches(-1);
    } else if (currentKeyword) {
      highlightKeyword(currentKeyword, request.color || '#ffff00');
    }
    sendResponse({ currentMatchIndex, totalMatches });
  }
  return true;
});

function highlightKeyword(keyword, color, isAutoHighlight = false) {
  if (!isAutoHighlight) {
    clearHighlights();
  }
  
  const regex = new RegExp(keyword, 'gi');
  
  // 获取所有文本节点，但排除已高亮的内容
  const walker = document.createTreeWalker(
    document.body,
    NodeFilter.SHOW_TEXT,
    {
      acceptNode: function(node) {
        const style = window.getComputedStyle(node.parentElement);
        if (style.display === 'none' || 
            style.visibility === 'hidden' || 
            style.opacity === '0' || 
            node.textContent.trim() === '' ||
            node.parentElement.classList.contains('highlight-extension')) {
          return NodeFilter.FILTER_REJECT;
        }
        return NodeFilter.FILTER_ACCEPT;
      }
    },
    false
  );

  const nodes = [];
  let node;
  while (node = walker.nextNode()) {
    nodes.push(node);
  }

  if (!isAutoHighlight) {
    totalMatches = 0;
    currentHighlights = [];
  }

  nodes.forEach(node => {
    const parent = node.parentNode;
    if (parent.tagName !== 'SCRIPT' && parent.tagName !== 'STYLE' && 
        !parent.classList.contains('highlight-extension')) {
      const content = node.textContent;
      if (content.match(regex)) {
        const span = document.createElement('span');
        span.innerHTML = content.replace(regex, match => {
          const highlightSpan = `<span class="highlight-extension" 
            data-match-index="${totalMatches}" 
            style="background-color: ${color}; font-weight: bold;">${match}</span>`;
          totalMatches++;
          return highlightSpan;
        });
        parent.replaceChild(span, node);
      }
    }
  });

  currentHighlights = Array.from(document.querySelectorAll('.highlight-extension'));

  if (totalMatches > 0 && !isAutoHighlight) {
    currentMatchIndex = 0;
    scrollToMatch(currentMatchIndex);
  }
}

function autoHighlightKeyPhrases() {
  clearHighlights();
  totalMatches = 0;
  currentHighlights = [];
  
  // 获取所有文本节点
  const textNodes = getAllTextNodes();
  const allMatches = [];

  // 第一步：收集所有匹配
  textNodes.forEach(textNode => {
    const content = textNode.textContent;
    Object.entries(keyPhraseRules).forEach(([type, rule]) => {
      rule.patterns.forEach(pattern => {
        const matches = findMatches(content, pattern, type, rule.color);
        allMatches.push(...matches.map(match => ({
          ...match,
          node: textNode
        })));
      });
    });
  });

  // 第二步：按长度排序并处理重叠
  const validMatches = filterOverlappingMatches(allMatches);

  // 第三步：应用高亮
  applyHighlights(validMatches);

  // 更新状态
  if (totalMatches > 0) {
    currentMatchIndex = 0;
    scrollToMatch(currentMatchIndex);
  }
}

// 获取所有有效的文本节点
function getAllTextNodes() {
  const walker = document.createTreeWalker(
    document.body,
    NodeFilter.SHOW_TEXT,
    {
      acceptNode: function(node) {
        if (!isValidTextNode(node)) {
          return NodeFilter.FILTER_REJECT;
        }
        return NodeFilter.FILTER_ACCEPT;
      }
    }
  );

  const nodes = [];
  let node;
  while (node = walker.nextNode()) {
    nodes.push(node);
  }
  return nodes;
}

// 检查文本节点是否有效
function isValidTextNode(node) {
  const parent = node.parentNode;
  if (!parent) return false;

  // 检查父元素是否可见
  const style = window.getComputedStyle(parent);
  if (style.display === 'none' || 
      style.visibility === 'hidden' || 
      style.opacity === '0') {
    return false;
  }

  // 检查是否是脚本或样式标签
  if (parent.tagName === 'SCRIPT' || 
      parent.tagName === 'STYLE' || 
      parent.classList.contains('highlight-extension')) {
    return false;
  }

  // 检查文本内容是否为空
  return node.textContent.trim() !== '';
}

// 在文本中查找匹配
function findMatches(content, pattern, type, color) {
  const matches = [];
  let regex;

  if (pattern.includes('.*?')) {
    const parts = pattern.split('.*?');
    regex = new RegExp(`(${parts[0]}[^。！？.!?]{0,50}?${parts[1]})`, 'gi');
  } else {
    regex = new RegExp(`([^。！？.!?]*?${pattern}[^。！？.!?]*?)`, 'gi');
  }

  let match;
  while ((match = regex.exec(content)) !== null) {
    const sentence = match[1].trim();
    matches.push({
      text: sentence,
      index: match.index,
      length: sentence.length,
      type,
      color
    });
  }

  return matches;
}

// 过滤重叠的匹配
function filterOverlappingMatches(matches) {
  // 按长度降序排序
  matches.sort((a, b) => b.length - a.length);

  const validMatches = [];
  const usedRanges = new Map(); // 使用 Map 存储每个节点的使用范围

  matches.forEach(match => {
    const nodeRanges = usedRanges.get(match.node) || [];
    const range = [match.index, match.index + match.length];
    
    const overlaps = nodeRanges.some(([start, end]) => 
      !(range[1] <= start || range[0] >= end)
    );

    if (!overlaps) {
      validMatches.push(match);
      nodeRanges.push(range);
      usedRanges.set(match.node, nodeRanges);
    }
  });

  return validMatches;
}

// 应用高亮
function applyHighlights(matches) {
  // 按节点分组
  const nodeMatches = new Map();
  matches.forEach(match => {
    const arr = nodeMatches.get(match.node) || [];
    arr.push(match);
    nodeMatches.set(match.node, arr);
  });

  // 处理每个节点
  nodeMatches.forEach((nodeMatches, textNode) => {
    const content = textNode.textContent;
    let html = content;
    let offset = 0;

    // 按位置排序
    nodeMatches.sort((a, b) => a.index - b.index);

    nodeMatches.forEach(match => {
      const before = html.substring(0, match.index + offset);
      const after = html.substring(match.index + offset + match.text.length);
      const highlightHtml = `<span class="highlight-extension" 
        data-match-index="${totalMatches}" 
        data-type="${match.type}"
        style="background-color: ${match.color}; font-weight: bold;">${match.text}</span>`;
      
      html = before + highlightHtml + after;
      offset += highlightHtml.length - match.text.length;
      totalMatches++;
    });

    const span = document.createElement('span');
    span.innerHTML = html;
    textNode.parentNode.replaceChild(span, textNode);
  });

  // 更新高亮元素列表
  currentHighlights = Array.from(document.querySelectorAll('.highlight-extension'));
}

function navigateMatches(direction) {
  if (totalMatches === 0 || !currentHighlights.length) return;

  currentMatchIndex = (currentMatchIndex + direction + totalMatches) % totalMatches;
  scrollToMatch(currentMatchIndex);
}

function scrollToMatch(index) {
  if (!currentHighlights.length) {
    currentHighlights = Array.from(document.querySelectorAll('.highlight-extension'));
  }

  // 移除所有高亮的特殊样式
  currentHighlights.forEach(h => {
    h.style.outline = 'none';
    h.style.boxShadow = 'none';
  });
  
  const currentMatch = currentHighlights[index];
  if (currentMatch) {
    // 添加当前选中项的视觉效果
    currentMatch.style.outline = '2px solid #FF4081';
    currentMatch.style.boxShadow = '0 0 8px rgba(255,64,129,0.5)';

    // 获取类型并转换为中文
    const type = currentMatch.dataset.type;
    const typeText = {
      transition: '转折句式',
      causation: '因果关系',
      progression: '递进强调',
      summary: '总结归纳',
      comparison: '对比句式',
      emphasis: '重点强调',
      definition: '定义举例'
    }[type] || '';

    // 发送消息更新计数和类型显示
    chrome.runtime.sendMessage({ 
      action: 'updateCount', 
      total: totalMatches, 
      current: currentMatchIndex,
      type: typeText
    });

    // 滚动到当前匹配项
    const rect = currentMatch.getBoundingClientRect();
    const isInViewport = (
      rect.top >= 0 &&
      rect.left >= 0 &&
      rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
      rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );

    if (!isInViewport) {
      currentMatch.scrollIntoView({
        behavior: 'smooth',
        block: 'center'
      });
    }
  }
}

// 添加键盘快捷键支持
document.addEventListener('keydown', (e) => {
  if (e.key === 'F3' || (e.ctrlKey && e.key.toLowerCase() === 'g')) {
    e.preventDefault();
    if (e.shiftKey) {
      chrome.runtime.sendMessage({ action: 'prevMatch' });
    } else {
      chrome.runtime.sendMessage({ action: 'nextMatch' });
    }
  } else if (e.ctrlKey && e.key.toLowerCase() === 'f') {
    e.preventDefault();
    chrome.runtime.sendMessage({ action: 'openPopup' });
  }
});

function clearHighlights() {
  const highlights = document.querySelectorAll('.highlight-extension');
  highlights.forEach(highlight => {
    const parent = highlight.parentNode;
    const text = document.createTextNode(highlight.textContent);
    parent.replaceChild(text, highlight);
  });

  // 清理可能的嵌套 span
  document.querySelectorAll('span:not([class])').forEach(span => {
    if (span.innerHTML === span.textContent) {
      const parent = span.parentNode;
      const text = document.createTextNode(span.textContent);
      parent.replaceChild(text, span);
    }
  });
} 